import {message} from "antd";

let socket: WebSocket | null = null;
let reconnectAttempts = 0;
const MAX_RECONNECT_ATTEMPTS = 5;

/**
 * 初始化 WebSocket 连接并监听消息
 * @param userId 用户ID
 * @param onMessage 接收到消息后的回调
 */
export const startWebSocketConnection = (
  userId: string | number,
  onMessage: (message: string) => void,
) => {
  if (socket) {
    socket.close(); // 如果已有连接，先关闭
  }

  const connect = () => {
    socket = new WebSocket(`ws://localhost:8080/api/applet/websocket/myWebSocketHandler`);

    socket.onopen = () => {
      console.log('WebSocket 连接已建立');
      reconnectAttempts = 0;
      socket?.send(JSON.stringify({ userId: userId }));
    };

    socket.onclose = () => {
      console.log('WebSocket 连接已关闭');
      if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
        reconnectAttempts++;
        console.log(`尝试第 ${reconnectAttempts} 次重连...`);
        setTimeout(connect, 3000);
      }
    };

    socket.onerror = (error) => {
      console.error('WebSocket 错误:', error);
    };

    socket.onmessage = (event) => {
      // 通过回调处理接收到的消息
      onMessage(event.data);
    };
  };

  connect();
};

/**
 * 关闭 WebSocket 连接
 */
export const closeWebSocketConnection = () => {
  if (socket) {
    socket.close();
    socket = null;
  }
};
